import React, { useCallback, useMemo, useState } from 'react'
import { ListData, ListData2 } from '../../constants/Data';
import { TypeColors } from '../../constants/Data';
import { Button, FlatList, StyleSheet, Switch, Text, TouchableOpacity, View } from 'react-native';


export default function ConsumeList() {
  const [data, setData] = useState<any>(ListData);
  const [showType, setShowType] = useState<boolean>(true);

  const click = () => {
    console.log('click');
  }



  // 1. useMemo的使用 -- 缓存数据
  // 仅仅切换 类型 显示不显示  则不需要重新计算 使用useMemo包裹计算方法
  const calculateTotal = useMemo(() => {
    console.log('重新计算合计');
    return data.map((item: any) => item.amount)
      .reduce((pre: number, cur: number) => pre + cur);
  }, [data])


  // 2. useMemo的使用 -- 缓存组件
  const totalAmountView = useMemo(() => {
    const total = data.map((item: any) => item.amount)
      .reduce((pre: number, cur: number) => pre + cur);
    console.log('重新渲染合计');
    return (
      <View style={styles.totalLayout}>
        <Text style={styles.totalTxt}>{total}</Text>
        <Text style={styles.totalTxt}>总金额：</Text>
      </View>
    );
  }, [data])

  // 3. useCallback  缓存函数  提高性能
  const onItemPress = useCallback((item: any) => () => {
    console.log(`点击第${item.id}行`);
  }, [])


  const renderItem = ({ item }: any) => {
    return (
      <TouchableOpacity
        style={styles.itemLayout}
        onPress={onItemPress(item)}
      >
        <View style={styles.labelRow}>
          <Text style={[styles.labelTxt, styles.first]}>序号</Text>
          {
            showType && <Text style={[styles.labelTxt, styles.second]}>类型</Text>
          }

          <Text style={[styles.labelTxt]}>消费名称</Text>
          <Text style={[styles.labelTxt, styles.last]}>消费金额</Text>
        </View>
        <View style={[styles.labelRow, styles.valueRow]}>
          <Text style={[styles.valueTxt, styles.first]}>{item.index}</Text>
          {
            showType && <View style={styles.typeLayout}>
              <Text style={[
                styles.typeTxt,
                // typeof 操作符获取 Icons 变量的类型，然后通过 keyof 操作符获取该类型的所有键。
                { backgroundColor: TypeColors[item.type as keyof typeof TypeColors] }
              ]}>
                {item.type}
              </Text>
            </View>
          }

          <Text style={styles.valueTxt}>{item.name}</Text>
          <Text style={[styles.valueTxt, styles.last]}>{item.amount}</Text>
        </View>
      </TouchableOpacity>
    )
  }


  return (
    <View style={styles.root}>
      <View style={styles.titleLayout}>
        <Text style={styles.titleText}>
          消费记账薄
        </Text>
        <Button title={'clickme'} onPress={() => setData(ListData2)} />

        <Switch
          style={styles.switch}
          value={showType}
          onValueChange={value => setShowType(value)}
        />
      </View>

      {/* 给FlatList 自定义高度时， 必须设置 flexGrow 为0  */}
      <FlatList
        style={{ height: '100%', flexGrow: 0 }}
        data={data}
        keyExtractor={item => item.id}
        renderItem={renderItem}
      />
      {/* <View style={styles.totalLayout}>
        <Text style={styles.totalTxt}>{calculateTotal} </Text>
        <Text style={styles.totalTxt}>合计：</Text>
      </View> */}
      {totalAmountView}
    </View>
  )
}

const styles = StyleSheet.create({
  root: {
    width: '100%',
    height: '100%',
    backgroundColor: '#efefef'
  },
  titleLayout: {
    width: '100%',
    height: 56,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center'
  },
  titleText: {
    fontSize: 18,
    fontWeight: '500'
  },
  itemLayout: {
    width: '100%',
    padding: 16,
    flexDirection: 'column',
    borderBottomWidth: 1,
    borderBottomColor: '#E0E0E0',
  },
  labelRow: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
  },
  valueRow: {
    marginTop: 10,
  },
  labelTxt: {
    flex: 1,
    fontSize: 14,
    color: '#666',
  },
  first: {
    flex: 0.3,
  },
  second: {
    flex: 0.3,
  },
  last: {
    flex: 0.5
  },
  valueTxt: {
    flex: 1,
    fontSize: 16,
    color: '#333',

  },
  typeLayout: {
    flex: 0.3,
  },
  typeTxt: {
    width: 20,
    height: 20,
    textAlign: 'center',
    textAlignVertical: 'center',
    color: '#fff',
    borderRadius: 4,

  },
  switch: {
    position: 'absolute',
    right: 16,
  },
  totalLayout: {
    width: '100%',
    height: 50,
    flexDirection: 'row-reverse',
    borderTopWidth: 1,
    borderTopColor: '#c0c0c0',
    alignItems: 'center',
    paddingHorizontal: 16,
    backgroundColor: '#d8ded8'
  },
  totalTxt: {
    fontSize: 18,
    color: '#333',
  },
})